var $container = $('#container');
var page = 1;
var limit = 20;
var setImgWidth = 400;

function link(url) {
	window.open(url);
}

$(document).ready(function() {
	setRender();
	$("#btnMore").click(function() {
		addRender();
	});
	
	setInterval(function() {
		$(".item img").each(function() {
	        var imgWidth = $(this).width();
	        if (imgWidth > setImgWidth) {
	        	$(this).css("width", setImgWidth+"px");
	        }
		});
	}, 500);
	
});
function getData() {
	var result;
	if(!page || !limit) {
		return false;
	}

	$.ajax({
	    url : './getcartoon.php',
	    dataType : "json",
	    type : "get",
	    //jsonp : "callback",
	    async : false,
	    data : {
	    	page :		page,
	    	limit :		limit
	    },
	    success : function(data){
	    	result = data;
	    },
	    error : function() {
	    	alert("error");
	    },
	    complete : function() {
		    //alert("complete");
	    }
	});
	return result;
}
function setRender() {
	var data = getData();
	var renderData = render(data);
	$("#container").append(renderData);
	setInterval(function() {
		animating();
	}, 500);
	setTimeout(function() {
		$("#footer").show("slow");
	}, 3000);
}
function addRender() {
	page = page + 1;
	var data = getData();
	var $renderData = $(render(data)).css({ opacity: 0 });
	if(data.result == "success") {
		var msg = '<img src="images/ajax-loader.gif"><br /><span class="msg">Loading the next set of cartoons...</span>';
		
	} else if(data.result == "fail") {
		var msg = '<span class="msg">No more cartoons to load</span>'; 
	}
	$.blockUI({ 
        message: msg, 
        timeout: 3000,
        css: { 
            backgroundColor: '#ffffff', 
            opacity: .6, 
            cursor:	null
        }  
    });
	$renderData.animate({ opacity: 1 });
	setTimeout(function() {
		$("#container").append( $renderData ).masonry( 'appended', $renderData, true );
	}, 2000);
}
function render(data) {
	var count = data.count;
	var items = data.items;
	var str = '';
	for(var i = 0; i < count; i++) {
		str += '<div class="item pointer" onClick=\'link("'+items[i].link+'");\'>';
		//str += '	<a href="'+items[i].img+'" ref="lightbox" onClick="return false;"';
		str += '		<img src="'+items[i].img+'" />';
		//str += '	</a>';
		str += '	<div class="text">'+items[i].title+'</div>';
		str += '</div>';
	}
	return str;
}
function animating() {
	$('#container').masonry({
		itemSelector : '.item',
	    columnWidth : 440,
	    isAnimated: true
	});
}

//스크롤 이벤트
/*
$(window).scroll(function(){ 
	d_top = $(document).height(); // document height
	w_top = $(window).height();  // window height
	n_top = $(document).scrollTop(); // document top
	if ((d_top - w_top - n_top) < 1) {
		addRender();
	}
});
*/